<!--
 * @Description:
 * @Author: 月间
 * @Date: 2024-10-14 21:07:53
 * @LastEditTime: 2025-03-30 00:34:49
 * @LastEditors:
-->
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import {
  fetchAddUser,
  fetchGetAllPost,
  fetchGetAllRoles,
  fetchGetDepartmentTree,
  fetchUpdateUser
} from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions, userGenderOptions } from '@/constants/business';

defineOptions({
  name: 'UserOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.User | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.user.addUser'),
    edit: $t('page.manage.user.editUser')
  };
  return titles[props.operateType];
});

type Model = Api.SystemManage.UserUpdate;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    username: '',
    sex: null,
    nickname: '',
    phone: null,
    email: null,
    roleIds: [],
    status: null,
    password: '123456',
    isSuper: '0',
    remark: null,
    postIds: [],
    deptId: null
  };
}

// 提取对应的key
type RuleKey = Extract<keyof Model, 'username' | 'status' | 'password' | 'postIds' | 'deptId'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  username: defaultRequiredRule,
  status: defaultRequiredRule,
  password: defaultRequiredRule,
  postIds: defaultRequiredRule, // 添加岗位必填规则
  deptId: defaultRequiredRule // 添加部门必填规则
};

/** the enabled role options */
const roleOptions = ref<CommonType.Option<string | number>[]>([]);

async function getRoleOptions() {
  const { error, data } = await fetchGetAllRoles();

  if (!error) {
    const options = data.map(item => ({
      label: item.roleName,
      value: item.id
    }));

    // the mock data does not have the roleCode, so fill it
    // if the real request, remove the following code
    // const userRoleOptions = model.userRoles.map(item => ({
    //   label: item,
    //   value: item
    // }));
    // end

    roleOptions.value = [...options];
  }
}
const postOptions = ref<CommonType.Option[]>([]);
// 查询所有岗位options
async function getPostOptions() {
  const { error, data } = await fetchGetAllPost();

  if (!error) {
    postOptions.value = data;
  }
}

// 部门树options
const departmentOptions = ref<Api.SystemManage.Dept[]>([]);

async function getDepartmentOptions() {
  const { error, data } = await fetchGetDepartmentTree();
  if (!error) {
    departmentOptions.value = data;
  }
}

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request
  // 判断id是否存在，存在则更新，不存在则新增
  let data = null;
  if (model.id) {
    data = await fetchUpdateUser(model);
  } else {
    data = await fetchAddUser(model);
  }
  const { error } = data;
  if (error) return;
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
    getPostOptions();
    getDepartmentOptions();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem :label="$t('page.manage.user.userName')" path="username">
          <NInput v-model:value="model.username" :placeholder="$t('page.manage.user.form.userName')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userGender')" path="sex">
          <NRadioGroup v-model:value="model.sex">
            <NRadio v-for="item in userGenderOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.nickName')" path="nickname">
          <NInput v-model:value="model.nickname" :placeholder="$t('page.manage.user.form.nickName')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userPhone')" path="phone">
          <NInput v-model:value="model.phone" :placeholder="$t('page.manage.user.form.userPhone')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userEmail')" path="email">
          <NInput v-model:value="model.email" :placeholder="$t('page.manage.user.form.userEmail')" />
        </NFormItem>
        <NFormItem label="密码" path="password">
          <NInput v-model:value="model.password" placeholder="请输入密码" type="password" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userStatus')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userRole')" path="roles">
          <NSelect
            v-model:value="model.roleIds"
            multiple
            :options="roleOptions"
            :placeholder="$t('page.manage.user.form.userRole')"
          />
        </NFormItem>
        <NFormItem label="岗位" path="postIds">
          <NSelect v-model:value="model.postIds" multiple :options="postOptions" placeholder="请选择用户岗位" />
        </NFormItem>
        <NFormItem label="部门" path="deptId">
          <NTreeSelect
            v-model:value="model.deptId"
            label-field="deptName"
            key-field="id"
            :options="departmentOptions"
            placeholder="请选择用户部门"
          />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
